<template>
  <view class="container">
    <!-- 大卡片 -->
    <view class="business-card" v-if="!hasMessages">
      <image class="bg-img" src="/static/biejing.png" mode="aspectFill" />
      <view class="info">
        <view class="name-section">
          <text class="name">高逊</text>
          <text class="slogan">董事长</text>
        </view>
        <view class="contact">
          <view class="contact-item">
            <text>引力琥珀人工智能</text>
          </view>
          <view class="contact-item">
            <text>郑州引力琥珀人工智能科技有限公司</text>
          </view>
          <view class="contact-item">
            <text> </text>
          </view>
        </view>
        <text class="service-title"> </text>
        <text class="service-content">13523432733</text>
      </view>
    </view>

    <!-- 小卡片 -->
    <view class="compact-card" v-if="hasMessages">
      <view class="gradient-bar">
        <text class="name">高逊</text>
        <text class="slogan">董事长</text>
        <text class="company">引力琥珀人工智能科技有限公司</text>
        <uni-icons type="phone" size="20" color="#fff"></uni-icons>
      </view>
    </view>
    <!-- 图标功能区 -->
    <view class="icon-row" v-if="!hasMessages">
      <view class="icon-col">
        <image src="/static/aihao.png" class="icon-main" />
        <text class="icon-label">爱好</text>
      </view>
      <view class="icon-col">
        <image src="/static/hezuo.png" class="icon-main" />
        <text class="icon-label">合作</text>
      </view>
      <view class="icon-col">
        <image src="/static/gongxu.png" class="icon-main" />
        <text class="icon-label">供需</text>
      </view>
    </view>
    <!-- 热门词条区域 -->
    <view class="hot-keywords" v-if="!hasMessages">
      <view class="keywords-list">
        <view v-for="(keyword, index) in hotKeywords" :key="index" class="keyword-item"
          @tap="startChatWithKeyword(keyword)">
          <text>{{ keyword }}</text>
        </view>
      </view>
    </view>
    <!-- 聊天记录区域 -->
    <scroll-view class="chat-container" scroll-y :scroll-top="scrollTop" :scroll-with-animation="true"
      @scrolltoupper="loadMoreMessages" :scroll-into-view="lastMessageId" :scroll-anchoring="true" :enhanced="true"
      :bounces="true" :show-scrollbar="false" :scroll-animation-duration="300">
      <view class="message-list">
        <view v-for="(message, index) in messages" :key="index" :id="'msg-' + index"
          :class="['message-item', message.type === 'user' ? 'message-user' : 'message-ai']">
          <view class="message-content">
            <text v-if="message.type === 'user'">{{ message.content }}</text>
            <view v-else class="stream-content">
              <text>{{ message.content }}</text>
              <text v-if="message.isStreaming" class="streaming-indicator">▋</text>

            </view>
          </view>
          <text class="message-time">{{ message.time }}</text>
        </view>
      </view>
    </scroll-view>

    <!-- 输入框区域 -->
    <view class="input-container" :style="{ bottom: keyboardHeight + 'px' }">
      <view class="input-box">
        <input v-model="inputMessage" type="text" placeholder="请输入您的问题" confirm-type="send" @confirm="sendMessage"
          :adjust-position="false" :cursor-spacing="20" @focus="onFocus" @blur="onBlur" :disabled="isSending" />
        <button class="send-btn" @tap="sendMessage" :disabled="isSending">
          {{ isSending ? '发送中...' : '发送' }}
        </button>
      </view>
    </view>

    <!-- 用于生成分享图片的画布 -->
    <canvas canvas-id="shareCanvas" class="share-canvas"
      :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }"></canvas>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import { useCompanyStore } from '@/stores/company'
import { useTalkHis } from '@/stores/talkHis'
import { Api_key, BaseUrl } from '@/utils/RobApi'
import { ChatService } from '@/utils/chatService'

// 获取企业信息
const companyStore = useCompanyStore()
const talkHisStore = useTalkHis()
const chatService = new ChatService()

// 热门词条
const hotKeywords = ref([
  '了解商业方向',
  '了解对方的兴趣爱好',
  '看看我们之间有哪些可聊的话题',
  '公司主管的信息'
])

// 使用关键词开始聊天
const startChatWithKeyword = (keyword: string) => {
  inputMessage.value = keyword
  sendMessage()
}

// 画布尺寸
const canvasWidth = 750
const canvasHeight = 1000
interface Message {
  type: 'user' | 'ai'
  content: string
  time: string
  isStreaming?: boolean
}

// 消息列表
const messages = ref<Message[]>([])
const inputMessage = ref('')
const keyboardHeight = ref(0)
const scrollTop = ref(0)
const hasMessages = computed(() => messages.value.length > 0)
const isSending = ref(false)
const lastMessageId = ref('')

// 监听消息列表变化，自动滚动到最新消息
watch(messages, () => {
  nextTick(() => {
    if (messages.value.length > 0) {
      lastMessageId.value = 'msg-' + (messages.value.length - 1)
      scrollToBottom()
    }
  })
}, { deep: true })

// 在消息内容更新时也触发滚动
watch(() => messages.value.map(m => m.content).join(''), () => {
  nextTick(() => {
    if (messages.value.length > 0) {
      lastMessageId.value = 'msg-' + (messages.value.length - 1)
      scrollToBottom()
    }
  })
})

// 生成分享图片
const generateShareImage = async () => {
  const ctx = uni.createCanvasContext('shareCanvas')

  // 绘制背景
  ctx.setFillStyle('#1f2128')
  ctx.fillRect(0, 0, canvasWidth, canvasHeight)

  // 绘制渐变背景
  const gradient = ctx.createLinearGradient(0, 0, canvasWidth, canvasHeight)
  gradient.addColorStop(0, '#1b1b2f')
  gradient.addColorStop(0.5, '#252d3a')
  gradient.addColorStop(1, '#2a2a3e')
  ctx.setFillStyle(gradient)
  ctx.fillRect(0, 0, canvasWidth, canvasHeight)

  // 绘制企业Logo
  if (companyStore.companyInfo.logo) {
    const logoSize = 160
    const logoX = (canvasWidth - logoSize) / 2
    const logoY = 100
    ctx.save()
    ctx.beginPath()
    ctx.arc(logoX + logoSize / 2, logoY + logoSize / 2, logoSize / 2, 0, Math.PI * 2)
    ctx.clip()
    ctx.drawImage(companyStore.companyInfo.logo, logoX, logoY, logoSize, logoSize)
    ctx.restore()
  }

  // 绘制企业名称
  ctx.setFontSize(48)
  ctx.setFillStyle('#ffffff')
  ctx.setTextAlign('center')
  ctx.fillText(companyStore.companyInfo.name || '引力琥珀', canvasWidth / 2, 320)

  // 绘制企业标语
  ctx.setFontSize(28)
  ctx.setFillStyle('#cccccc')
  ctx.fillText(companyStore.companyInfo.slogan || '语言的智能，才能替代智能语言', canvasWidth / 2, 380)

  // 绘制联系方式
  const contactInfo = [
    `电话：${companyStore.companyInfo.phone || '11111111'}`,
    `邮箱：${companyStore.companyInfo.email || '5xxxxxx@qq.com'}`,
    `网址：${companyStore.companyInfo.website || 'https://52d47b77.r34.cpolar.top'}`
  ]

  ctx.setFontSize(24)
  ctx.setTextAlign('left')
  contactInfo.forEach((info, index) => {
    ctx.fillText(info, 100, 450 + index * 40)
  })

  // 绘制业务内容
  ctx.setFontSize(32)
  ctx.setFillStyle('#646cff')
  ctx.fillText('业务内容', 100, 600)

  ctx.setFontSize(28)
  ctx.setFillStyle('#ffffff')
  ctx.fillText(companyStore.companyInfo.business || '我们的业务', 100, 650)

  // 绘制二维码提示
  ctx.setFontSize(24)
  ctx.setFillStyle('#999999')
  ctx.setTextAlign('center')
  ctx.fillText('长按识别二维码了解更多', canvasWidth / 2, 900)

  // 绘制小程序码
  if (companyStore.companyInfo.qrcode) {
    const qrcodeSize = 200
    const qrcodeX = (canvasWidth - qrcodeSize) / 2
    const qrcodeY = 700
    ctx.drawImage(companyStore.companyInfo.qrcode, qrcodeX, qrcodeY, qrcodeSize, qrcodeSize)
  }

  // 完成绘制
  ctx.draw(false, () => {
    // 将画布内容转换为图片
    uni.canvasToTempFilePath({
      canvasId: 'shareCanvas',
      success: (res) => {
        // 更新分享图片
        companyStore.setShareImage(res.tempFilePath)
      },
      fail: (err) => {
        console.error('生成分享图片失败：', err)
        uni.showToast({
          title: '生成分享图片失败',
          icon: 'none'
        })
      }
    })
  })
}

// 添加平台判断函数
const decodeResponseData = (data: string | ArrayBuffer): string => {
  // #ifdef H5
  if (typeof TextDecoder !== 'undefined') {
    return new TextDecoder('utf-8').decode(data as ArrayBuffer)
  }
  // #endif

  // #ifdef MP-WEIXIN
  if (typeof data === 'string') {
    return data
  } else if (data instanceof ArrayBuffer) {
    let result = ''
    const uint8Array = new Uint8Array(data)
    for (let i = 0; i < uint8Array.length; i++) {
      result += String.fromCharCode(uint8Array[i])
    }
    return result
  }
  return ''
  // #endif
}

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim() || isSending.value) return

  isSending.value = true
  const userMessage = inputMessage.value
  inputMessage.value = ''

  // 添加用户消息
  messages.value.push({
    type: 'user',
    content: userMessage,
    time: new Date().toLocaleTimeString()
  })

  // 添加AI消息占位
  const aiMessageIndex = messages.value.length
  messages.value.push({
    type: 'ai',
    content: '',
    time: new Date().toLocaleTimeString(),
    isStreaming: true
  })

  // 立即滚动到底部
  scrollToBottom()

  try {
    await chatService.sendMessage(
      userMessage,
      (message) => {
        messages.value[aiMessageIndex] = message
        scrollToBottom()
      },
      () => {
        isSending.value = false
      }
    )
  } catch (error) {
    console.error('发送消息失败:', error)
    messages.value[aiMessageIndex].content = '抱歉，发送消息失败，请重试'
    messages.value[aiMessageIndex].isStreaming = false
    isSending.value = false
  }
}

// 修改滚动逻辑，使其在不同平台都能正常工作
const scrollToBottom = () => {
  // #ifdef H5
  const container = document.querySelector('.chat-container')
  if (container) {
    container.scrollTo({
      top: container.scrollHeight,
      behavior: 'smooth'
    })
  }
  // #endif

  // #ifdef MP-WEIXIN
  // 触发 scroll-view 的 scroll-into-view 到最新消息
  scrollTop.value = scrollTop.value + 1 // 触发更新
  // #endif
}

// 加载更多消息
const loadMoreMessages = () => {
  // 实现加载历史消息的逻辑
  console.log('加载更多消息')
}

// 键盘事件处理
const onFocus = (e: any) => {
  // #ifdef MP-WEIXIN
  keyboardHeight.value = e.detail.height || 0
  // #endif
  // #ifdef H5
  keyboardHeight.value = 0
  // #endif
  scrollToBottom()
}

const onBlur = () => {
  keyboardHeight.value = 0
}

// 页面加载时
onMounted(() => {
  scrollToBottom()
  // 生成分享图片
  generateShareImage()
})
</script>

<style lang="scss">
/* 全局样式重置 */
page {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  overflow-x: hidden;
  background-color: #1f2128;
}

.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  width: 100%;
  box-sizing: border-box;
  position: relative;
  overflow-x: hidden;
}

/* 大卡片样式 */
.business-card {
  position: relative;
  border-radius: 20rpx;
  padding: 30rpx;
  margin: 30rpx;
  height: 350rpx;
  box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.1);
  box-sizing: border-box;
  overflow: hidden;

  .bg-img {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    z-index: 0;
    pointer-events: none;
  }

  .info {
    position: relative;
    z-index: 1;
    width: 100%;
  }

  .name-section {
    display: flex;
    align-items: center;
    gap: 20rpx;
  }

  .name {
    font-size: 48rpx;
    color: #fff;
    font-weight: bold;
    margin-bottom: 15rpx;
    display: block;
  }

  .slogan {
    font-size: 28rpx;
    color: #fff;
    margin-bottom: 15rpx;
    display: block;
  }

  .contact {
    margin: 20rpx 0;
  }

  .contact-item {
    display: flex;
    align-items: center;
    margin-bottom: 10rpx;

    text {
      color: #fff;
      font-size: 28rpx;
    }
  }

  .service-title {
    color: #fff;
    font-size: 32rpx;
    font-weight: bold;
    margin-top: 30rpx;
    display: block;
  }

  .service-content {
    color: #fff;
    font-size: 28rpx;
    margin-top: 20rpx;
    display: block;
  }
}

/* 小卡片样式 */
.compact-card {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  box-sizing: border-box;
  height: auto;
  min-height: 80rpx;
  justify-content: center;
  align-items: center;
  width: 820rpx;
  /* #ifdef H5 */
  position: sticky;
  top: 0;
  /* #endif */

  .gradient-bar {
    display: flex;
    align-items: center;
    border-radius: 40rpx;
    padding: 0 30rpx;
    height: 60rpx;
    background: linear-gradient(90deg, #7ed6df 0%, #70a1ff 50%, #e056fd 100%);
    color: #fff;
    font-size: 28rpx;
    font-weight: 400;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
    margin: 10rpx 20rpx;
    width: fit-content;
    min-width: 80%;
    // gap: 20rpx;
  }

  .gradient-bar .name {
    font-size: 32rpx;
    font-weight: bold;
    margin-right: 20rpx;
    // border-bottom: 2rpx solid #fff;
  }

  .gradient-bar .slogan {
    font-size: 24rpx;
    margin-right: 20rpx;
  }

  .gradient-bar .company {
    opacity: 0.9;
    font-size: 28rpx;
    margin-right: 20rpx;
  }
}

.icon-row {
  display: flex;
  // background-color: #fff;
  padding-left:50rpx;
  gap: 50rpx;
}

.icon-col {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 8rpx;
}

.icon-main {
  width: 32rpx;
  height: 32rpx;
}

.icon-label {
  font-size: 24rpx;
  color: #999;
}

/* 聊天容器样式 */
.chat-container {
  flex: 1;
  width: 100%;
  box-sizing: border-box;
  padding: 20rpx;
  overflow-y: auto;
  overflow-x: hidden;
  margin-top: 0;
  transition: margin-top 0.3s ease;
  padding-bottom: 120rpx;
  /* 增加底部内边距，为输入框留出空间 */
}

.compact-card+.chat-container {
  /* #ifdef H5 */
  margin-top: 40rpx;
  /* #endif */
  /* #ifdef MP-WEIXIN */
  margin-top: 120rpx;
  /* #endif */
}

.message-list {
  padding-bottom: 40rpx;
  /* 增加消息列表底部间距 */
  width: 100%;
  box-sizing: border-box;
}

.message-item {
  margin-bottom: 30rpx;
  display: flex;
  flex-direction: column;
  max-width: 100%;
  box-sizing: border-box;
}

.message-user {
  align-items: flex-end;
}

.message-ai {
  align-items: flex-start;
}

.message-content {
  max-width: 80%;
  padding: 20rpx;
  border-radius: 20rpx;
  font-size: 28rpx;
  word-break: break-all;
  box-sizing: border-box;
  white-space: pre-wrap;
  /* 保留换行符 */
}

.message-user .message-content {
  background-color: #646cff;
  color: #fff;
}

.message-ai .message-content {
  background-color: #3a3c4a;
  color: #fff;
}

.message-time {
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}

.input-container {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #2c2e3a;
  padding: 20rpx;
  transition: all 0.3s;
  box-sizing: border-box;
  width: 100%;
  z-index: 99;
  /* 确保输入框在消息之上 */
}

.input-box {
  display: flex;
  align-items: center;
  background-color: #3a3c4a;
  border-radius: 40rpx;
  padding: 10rpx 20rpx;
  box-sizing: border-box;
  width: 100%;

  input:disabled {
    opacity: 0.7;
  }
}

input {
  flex: 1;
  height: 80rpx;
  color: #fff;
  font-size: 28rpx;
  padding: 0 20rpx;
  box-sizing: border-box;
  width: 100%;
}

.send-btn {
  background-color: #646cff;
  color: #fff;
  font-size: 28rpx;
  padding: 10rpx 30rpx;
  border-radius: 30rpx;
  margin: 0;
  line-height: 1.5;
  white-space: nowrap;

  &:disabled {
    background-color: #999;
    opacity: 0.7;
  }
}

.send-btn::after {
  border: none;
}

/* 分享画布样式 */
.share-canvas {
  position: fixed;
  left: -9999px;
  top: -9999px;
  z-index: -1;
}

.hot-keywords {
  margin: 20rpx;
  padding: 20rpx;
}

.keywords-title {
  font-size: 32rpx;
  color: #646cff;
  font-weight: bold;
  margin-bottom: 20rpx;
  display: block;
}

.keywords-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.keyword-item {
  background-color: #3a3c4a;
  padding: 16rpx 30rpx;
  border-radius: 30rpx;
  font-size: 28rpx;
  color: #fff;
  transition: all 0.3s ease;
}

.keyword-item:active {
  background-color: #646cff;
  transform: scale(0.98);
}

.stream-content {
  display: inline-block;
  position: relative;
}

.streaming-indicator {
  display: inline-block;
  margin-left: 2px;
  animation: blink 1s infinite;
  color: #646cff;
}

@keyframes blink {

  0%,
  100% {
    opacity: 1;
  }

  50% {
    opacity: 0;
  }
}
</style>
